var $;
var layer;
var table;
var form;

    layui.use(['layer','table','form'], function () {
        layer=layui.layer;
        $=layui.jquery;
        table = layui.table;
        form=layui.form;

        //查询课程分类
        $.ajax({
            url:"/tea/selCourseClass",
            type:"get",
            dataType:"json",
            success:function(data){
                //初始化树
                ztree(data.obj);

                //初始化表格
                getUser();

                //初始化下拉框
                setclass(data.obj[0].children);

            },
            error: function () {
                layer.msg("数据获取失败！");
            }
        });

        //分类下拉框
        function setclass(data){
            for(var a=0;a<data.length;a++){
                if(data[a].children.length>0){//.addClass("opparent")
                    $("#searchClass").append("<option value='' disabled>---"+data[a].menuName+"---</option>");
                    setclass(data[a].children);
                }else{
                    $("#searchClass").append("<option value='"+data[a].nodeid+"'>"+data[a].menuName+"</option>");
                }
            }
            layui.form.render("select");//重新渲染
        }

        //获取用户信息
        function getUser() {
            $.post("/login/selUserContent", {}, function (res) {
                if (res.code>-1) {
                    $("#UserId").val(res.obj.userId);
                    var uId=$("#UserId").val();
                    getTab(uId,null,null,"",null,null,null,"");
                    //初始化总数按钮
                    getSum();
                } else {
                    layer.msg("数据加载失败", {icon: 2});
                }
            });
        }
        
        //总数按钮
        function getSum() {
            var uId=$("#UserId").val();
            $.ajax({
                url:"/tea/selCourseSum",
                type:"post",
                dataType:"json",
                data:{"uId":uId},
                success:function(data){
                    $("#allSum").text(data.obj.allSum);
                    $("#status2Sum").text(data.obj.status2Sum);
                    $("#status3Sum").text(data.obj.status3Sum);
                    $("#cstatus3Sum").text(data.obj.cstatus3Sum);
                    $("#cstatus5Sum").text(data.obj.cstatus5Sum);
                }
            });
        }

        //初始化ztree
        function ztree(data) {
            $(function () {
                var ZtreeTile;

                //点击节点获取值
                function zTreeOnClick(event, treeId, treeNode) {
                    var uId=$("#UserId").val();
                    getTab(uId,null,null,"",treeNode.nodeid,null,null,"");
                    $("#classId").val(treeNode.nodeid);
                    return false;
                };

                //右键工具栏
                function OnRightClick(event, treeId, treeNode) {
                    if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                        zTree.cancelSelectedNode();
                        showRMenu("root",event.clientX,event.clientY);
                    } else if (treeNode && !treeNode.noR) {
                        ZtreeTile = treeNode;
                        showRMenu("node", event.clientX, event.clientY);
                    }
                }

                function showRMenu(type, x, y) {
                    $("#rMenu ul").show();
                    if (type == "root") {
                        $("#m_del").hide();
                        $("#m_check").hide();
                        $("#m_unCheck").hide();
                    } else {
                        $("#m_del").show();
                        $("#m_check").show();
                        $("#m_unCheck").show();
                    }
                    //y += document.body.scrollTop;//document.body.scrollTop为0
                    //x += document.body.scrollLeft;//document.body.scrollLeft为0
                    x+=15;
                    y+=5;
                    rMenu.css({"top": y + "px", "left": x + "px", "display": "block"});
                    $("body").bind("mousedown", onBodyMouseDown);
                }

                function hideRMenu() {
                    if (rMenu) rMenu.css({"display": "block"});
                    $("body").unbind("mousedown", onBodyMouseDown);
                }

                function onBodyMouseDown(event) {
                    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
                        rMenu.css({"display": "block"});
                    }
                }

                //添加节点
                $("#m_add").on("click", function () {
                    hideRMenu();
                    //绑定添加事件，并定义添加操作
                    console.log(ZtreeTile);
                    var parentId = ZtreeTile.nodeid;
                    var uId = $("#UserId").val();
                    layer.open({
                        type: 1,
                        title: "添加节点",
                        area: ['400px', '180px'],
                        shade: 0.4,
                        offset: ['100px', '200px'],
                        content: "<div class='layerDiv'><p>分类名称:</p>"
                            + "<input type='text' name='title' required id='treeNode_id' lay-verify='required' placeholder='请输入标题' autocomplete='off' class='layui-input'></div>",
                        btn: ['添加', '取消'],
                        yes: function (index, layero) {
                            var name = $("#treeNode_id").val();
                            $.ajax({
                                url: "/tea/addClassTree",
                                type: "post",
                                dataType: "json",
                                data: {"parentId": parentId, "name": name,"uId":uId},
                                success: function (data) {
                                    if (data.code>-1) {
                                        layer.msg("课程添加成功", {icon: 1,time: 1000},function(){
                                            layer.close(index);
                                            location.reload();//刷新页面
                                        });
                                    } else{
                                        layer.msg("数据加载失败", {icon: 2});
                                    }
                                }
                            })
                        },
                        btn2: function (index, layero) {
                            rMenu.css({"display": "none"});
                            layer.close(index);
                        }
                    })
                })
                //修改节点
                $("#m_check").on("click", function () {
                    layer.open({
                        type: 1,
                        title: "修改节点",
                        area: ['400px', '180px'],
                        shade: 0.4,
                        offset: ['100px', '200px'],
                        content: "<div class='layerDiv'><p>分类名称:</p>"
                            + "<input type='text' name='title' required id='treeNode_id' value='"+ZtreeTile.menuName+"' lay-verify='required' placeholder='请输入标题' autocomplete='off' class='layui-input'></div>",
                        btn: ['修改', '取消'],
                        yes: function (index, layero) {
                            var id = ZtreeTile.nodeid;
                            var uId = $("#UserId").val();
                            var name = $("#treeNode_id").val();
                            $.ajax({
                                url: "/tea/updClassTree",
                                type: "post",
                                dataType: "json",
                                data: {"id": id, "name": name,"uId":uId},
                                success: function (data) {
                                    if (data.code>-1) {
                                        layer.msg("修改成功", {icon: 1,time: 1000},function(){
                                            layer.close(index);
                                            location.reload();//刷新页面
                                        });
                                    } else {
                                        layer.msg("数据加载失败", {icon: 2});
                                    }
                                }
                            })
                        },
                        btn2: function (index, layero) {
                            rMenu.css({"display": "none"});
                            layer.close(index);
                        }
                    })
                    hideRMenu();
                })
                //删除节点
                $("#m_del").on("click", function () {
                    hideRMenu();
                    var id = ZtreeTile.nodeid;
                    layer.open({
                        type: 1,
                        title: "删除节点",
                        area: ['200px', '180px'],
                        shade: 0.4,
                        offset:  ['100px', '200px'],
                        content:"<div class='layDiv'><p>确定删除分类<span>"+ZtreeTile.menuName+"</span>吗？</p></div>",
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {
                            $.post("/tea/delClassTree", {id: id}, function (res) {
                                if (res.code>-1) {
                                    layer.msg("课程删除成功", {icon: 1,time: 1000},function(){
                                        layer.close(index);
                                        location.reload();//刷新页面
                                    });
                                } else {
                                    layer.msg("数据加载失败", {icon: 2});
                                }
                            });
                        },
                        btn2: function (index, layero) {
                            rMenu.css({"display": "none"});
                            layer.close(index);
                        }
                    })
                })

                function resetTree() {
                    hideRMenu();
                    $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
                }

                var zTree, rMenu;
                $(document).ready(function () {
                    $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
                    zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.expandAll(true);
                    rMenu = $("#rMenu");
                });

                var setting = {
                    data: {//设置data属性
                        simpleData: {
                            enable: true, //true 、 false 分别表示 使用 、 不使用 简单数据模式
                            idKey: "nodeid", //节点数据中保存唯一标识的属性名称
                            pIdKey: "parentId",   //节点数据中保存其父节点唯一标识的属性名称
                            rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                        },
                        key: {
                            name: "menuName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                        }
                    },
                    check: {
                        chkStyle: "checkbox",//复选框类型
                        chkboxType: {"Y": "p", "N": "p"},//Y是勾选的时候对父结点或子结点产生的影响;N是取消的时候对父结点或子结点产生的影响;大小写是有区另的。s指子结点，p指父结点
                        enable: false, //true 、 false 分别表示 显示 、不显示 复选框或单选框
                        nocheckInherit: true
                    },
                    callback: {
                        onRightClick: OnRightClick,
                        onClick: zTreeOnClick,
                        beforeClick: validStatus
                    },
                    view: {
                        dblClickExpand: false,
                        showIcon: false
                    },
                };
                var zTreeNodes = data;
            })

            //禁止父节点点击
            function validStatus(treeId, treeNode, clickFlag) {
                if (treeNode.children.length > 0) {
                    layer.msg('不能选择父分类');
                    return false;
                }
                return true;
            };
        };


        //获取课程的数据
        function getTab(uId,status,cstatus,searchName,searchClass,searchPrice,num,courseIntro){
            $.ajax({
                url:"/tea/selcourseTab",
                type:"post",
                dataType:"json",
                contentType:"application/json",
                data:JSON.stringify({"uId":uId,"status":status,"cstatus":cstatus,"searchName":searchName,"searchClass":searchClass,"searchPrice":searchPrice,"num":num,"courseIntro":courseIntro}),
                success:function(data){
                    tab(data.obj);
                },
                error: function () {
                    layer.msg('数据获取失败！');
                }
            });
        }

        //表格
        function tab(data) {
            table.render({
                elem: '#courseTab',
                data:data
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: ['exports', { //自定义头部工具栏右侧图标
                    title: '导入'
                    ,layEvent: 'LAYTABLE_TIPS'
                    ,icon: 'layui-icon-file-b'
                }]
                ,title: '审核课程数据表'
                ,page:true
                ,limit:5
                //, size: 'sm'   //单元格大小
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field:'courseId',title:"编号",width:60,fixed:'left'}
                    ,{field:'url', title:'课程图片', width:100,templet(da){
                            return "<img src='"+da.url+"''/>";
                        }}
                    ,{field:'courseName', title:'课程名称', width:86}
                    ,{field:'createName', title:'上传人', width:72}
                    ,{field:'courseIntro', title:'简介', width:153}
                    ,{field:'courseNprice', title:'价格', width:60,templet(da){
                            return "<p>￥"+da.courseNprice+"</p>";
                        }}
                    ,{field:'courseStatus', title:'状态',width:95,templet(da){
                        if(da.courseCstatus==6){//已审核
                            if(da.courseStatus==2){//已上架
                                return "<input type='checkbox' name='courseStatus' value="+da.courseId+" lay-skin='switch' lay-text='上架|下架' checked  lay-filter='switchStatus'>";
                            }else{//未上架
                                return "<input type='checkbox' name='courseStatus' value="+da.courseId+" lay-skin='switch' lay-text='上架|下架' lay-filter='switchStatus'>";
                            }
                        }else{//未审核，不上架
                            return "<input type='checkbox' name='courseStatus' disabled lay-skin='switch' lay-text='上架|下架' lay-filter='switchStatus'>";
                        }
                    }}
                    ,{title:'排序',width:60,templet(da){//templet 通过这个函数可以实现逻辑处理，比如时间戳的转换
                            return da.LAY_INDEX;/*返回它的序列号*/}}
                    ,{field:'className', title:'分类',width:115}
                    ,{field:'saleNum', title:'销量',width:65,templet(da){
                            if(da.saleNum!=null&&da.saleNum!='') {
                                return "<p>"+da.saleNum+"</p>";
                            }else{
                                return "<p>0</p>";
                            }
                        }}
                    ,{field:'courseCstatus', title:'审核状态',width:133,templet(da){
                            if(da.courseCstatus==3){
                                return "<p>待审核</p>";
                            }else if(da.courseCstatus==4){
                                return "<p>审核中</p>";
                            }else if(da.courseCstatus==5){
                                return "<p>审核失败</p>";
                            }else if(da.courseCstatus==6){
                                return "<p>已审核<a href='#' onclick='javascript:getRecord("+da.courseId+")'>审核详情</a></p>";
                            }
                        }}
                    ,{title:'操作', width:180,templet(da){
                        return "<p><a onclick='javascript:getViewDetails("+da.courseId+")'>查看</a>" +
                            "<a onclick='javascript:setCourse("+da.courseId+")'>编辑</a>" +
                            "<a onclick='javascript:getJournal("+da.courseId+")'>日志</a>" +
                            "<a onclick='javascript:delCourse("+da.courseId+")'>删除</a></p>";
                    }}
                ]]
            });
        }


        //头工具栏事件
        table.on('toolbar(tab)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                //自定义头工具栏右侧图标 - 导入
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个导入');
                    break;
            };
        });


        //监听表格复选框选择//checked: false
    /*    table.on('checkbox(tab)', function(obj){
            //当前行课程的ID
            $("#courseId").val(obj.data.courseId);
        });
*/
        //监听指定开关//disabled
        form.on('switch(switchStatus)', function(data){
        //判断开关状态
            var state = data.elem.checked?2:3;
            updCourseCstatus(data.value,state);
        });

        //更改课程的上下架状态
        function updCourseCstatus(courseId,status){
            $.ajax({
                url:"/tea/updCourseStatus",
                type:"post",
                dataType:"json",
                data:{"courseId":courseId,"status":status},
                success:function(data){
                    if(data.code>-1){
                        layer.msg('状态更改成功', {icon: 1}, function(index){//关闭窗口并刷新页面
                            layer.close(index);
                            location.reload(true);
                        });
                    }else{
                        layer.msg('状态更改失败', {icon: 2});
                    }
                },
                error: function () {
                    layer.msg('数据出错！');
                }
            });
        };

        //全部课程按钮
        $("#allbut").on("click",function(){
            $("#allbut").removeClass("layui-btn-primary");
            $("#allSum").addClass("yesbut");
            $("#status2but").addClass("layui-btn-primary");
            $("#status2Sum").removeClass("yesbut");
            $("#status3but").addClass("layui-btn-primary");
            $("#status3Sum").removeClass("yesbut");
            $("#cstatus3but").addClass("layui-btn-primary");
            $("#cstatus3Sum").removeClass("yesbut");
            $("#cstatus5but").addClass("layui-btn-primary");
            $("#cstatus5Sum").removeClass("yesbut");
            var uId=$("#UserId").val();
            getTab(uId,null,null,"",null,null,null,"");
        });

        //已上架课程按钮
        $("#status2but").on("click",function(){
            $("#allbut").addClass("layui-btn-primary");
            $("#allSum").removeClass("yesbut");
            $("#status2but").removeClass("layui-btn-primary");
            $("#status2Sum").addClass("yesbut");
            $("#status3but").addClass("layui-btn-primary");
            $("#status3Sum").removeClass("yesbut");
            $("#cstatus3but").addClass("layui-btn-primary");
            $("#cstatus3Sum").removeClass("yesbut");
            $("#cstatus5but").addClass("layui-btn-primary");
            $("#cstatus5Sum").removeClass("yesbut");
            var uId=$("#UserId").val();
            getTab(uId,2,null,"",null,null,null,"");
        });

        //未上架课程按钮
        $("#status3but").on("click",function(){
            $("#allbut").addClass("layui-btn-primary");
            $("#allSum").removeClass("yesbut");
            $("#status2but").addClass("layui-btn-primary");
            $("#status2Sum").removeClass("yesbut");
            $("#status3but").removeClass("layui-btn-primary");
            $("#status3Sum").addClass("yesbut");
            $("#cstatus3but").addClass("layui-btn-primary");
            $("#cstatus3Sum").removeClass("yesbut");
            $("#cstatus5but").addClass("layui-btn-primary");
            $("#cstatus5Sum").removeClass("yesbut");
            var uId=$("#UserId").val();
            getTab(uId,3,null,"",null,null,null,"");
        });

        //待审核课程按钮
        $("#cstatus3but").on("click",function(){
            $("#allbut").addClass("layui-btn-primary");
            $("#allSum").removeClass("yesbut");
            $("#status2but").addClass("layui-btn-primary");
            $("#status2Sum").removeClass("yesbut");
            $("#status3but").addClass("layui-btn-primary");
            $("#status3Sum").removeClass("yesbut");
            $("#cstatus3but").removeClass("layui-btn-primary");
            $("#cstatus3Sum").addClass("yesbut");
            $("#cstatus5but").addClass("layui-btn-primary");
            $("#cstatus5Sum").removeClass("yesbut");
            var uId=$("#UserId").val();
            getTab(uId,null,3,"",null,null,null,"");
        });

        //未通过课程按钮
        $("#cstatus5but").on("click",function(){
            $("#allbut").addClass("layui-btn-primary");
            $("#allSum").removeClass("yesbut");
            $("#status2but").addClass("layui-btn-primary");
            $("#status2Sum").removeClass("yesbut");
            $("#status3but").addClass("layui-btn-primary");
            $("#status3Sum").removeClass("yesbut");
            $("#cstatus3but").addClass("layui-btn-primary");
            $("#cstatus3Sum").removeClass("yesbut");
            $("#cstatus5but").removeClass("layui-btn-primary");
            $("#cstatus5Sum").addClass("yesbut");
            var uId=$("#UserId").val();
            getTab(uId,null,5,"",null,null,null,"");
        });

        //查询按钮
        $("#queryButId").on("click",function(){
            var searchName=$("#searchName").val();
            var searchClass=$("#searchClass").val();
            var searchPrice=$("#searchPrice").val();
            var uId=$("#UserId").val();
            getTab(uId,null,null,searchName,searchClass,searchPrice,null,"");
        });

        //高级检索
        $("#retrievalButId").on("click",function(){
            layer.open({
                type:2,
                title:"高级检索",
                area:['450px','300px'],
                shade:0.4,
                offset:'auto',
                content:"CourseRretrieval.html"
            });
            window.layer_3=layer;//将当前弹出层的对象赋值给window对象
        });
        //检索出的表格
        setTab =function () {
            var courseIntro=$("#beizhu").val();
            var status=$("#status").val();
            var cstatus=$("#cstatus").val();
            var num=$("#num").val();
            var uId=$("#UserId").val();
            getTab(uId,status,cstatus,"",null,null,num,courseIntro);
        };

        //重置按钮
        $("#resetButId").on("click",function () {
            $("#searchName").val("");
            $("#searchClass").val("");
            $("#searchPrice").val("");
            var uId=$("#UserId").val();
            getTab(uId,null,null,"",null,null,null,"");
        });
    });
//添加课程
function addCourse() {
    var classid=$("#classId").val();
    if(classid){
          //window.location.href="";//页面跳转
          layer.open({
              type:2,
              title:"添加课程",
              area:['800px','600px'],
              shade:0.4,
              offset:'auto',
              maxmin: true,
              content:"TeaAddCourse.html",
              success:function(layero,index) {
                  //查找当前引入的iframe内容
                  var obj = layero.find('iframe').contents();
                  //根据选择器选择input,并设置值
                  obj.find('input[name=classId]').val(classid);
              },
              end:function () {
                  location.reload();
              }
          });
        //将当前弹出层的对象赋值给window对象
        window.layer_1=layer;
      }else{
          layer.msg("请先选择左侧课程分类，然后再进行添加", {icon: 2});
      }
}


//删除课程
function delCourse(id) {
    layer.open({
        type: 1,
        title: "删除课程",
        area: ['200px', '200px'],
        shade: 0.4,
        offset: 'auto',
        content:"<p id='layerpId'>确定删除该课程吗？</p>",
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            $.post("/tea/delCourse", {id: id}, function (res) {
                if (res.code>-1) {
                    layer.msg("课程删除成功", {icon: 1},function(){
                        layer.close(index);
                        location.reload();//刷新页面
                    });
                } else {
                    layer.msg("数据加载失败", {icon: 2});
                }
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    })
}

//查看课程日志
function getJournal(id) {
    layer.open({
        type:2,
        title:"课程日志",
        area:['1000px','210px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaCourseJournal.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=courseId]').val(id);
        }
    });
}

//编辑课程详情弹窗
function setCourse(id){
    layer.open({
        type:2,
        title:"编辑课程详情",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaEditCourse.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=courseId]').val(id);
        },
        end:function () {
            location.reload();
        }
    });
    //将当前弹出层的对象赋值给window对象
    window.layer_2=layer;
}


//课程详情弹窗
function getViewDetails(id) {
    layer.open({
        type:2,
        title:"课程详情",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaCourseView.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=courseId]').val(id);
        }
    });
}


//审核详情弹窗
function getRecord(Id) {
    layer.open({
        type:2,
        title:"审核详情",
        area:['700px','500px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaAuditdetails.html",
        success:function(layero,index) {
            var obj = layero.find('iframe').contents();//查找当前引入的iframe内容
            obj.find('input[name=courseId]').val(Id);//根据选择器选择input,并设置值
        }
    });
}

//刷新按钮
$("#breakbtn").on("click",function () {
    location.reload();//刷新页面
});
//返回按钮
$("#returnbtn").on("click",function () {
    history.go(-1);//数据全部还在 //history.back(-1)//直接返回当前页的上一页，是个新页面
});

